package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.Message;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Common.UUIDSliceRange;
import net.ib.mntalk.protocol.File.ImageOption;
import net.ib.mntalk.protocol.Session.GetMessagesReq;
import net.ib.mntalk.protocol.Session.GetMessagesRes;
import net.ib.mtalk.database.helper.ChatDatabaseHelper;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.ui.chat.ChatListActivity;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;

/**
 * COMMENT : 서버에 메시지가 있는지 확인하는 Task<br>
 * PRE-EXECUTE : View UUID로 서버에 GetMessage Envelope 작성<br>
 * POST-EXECUTE : ACK로 메시지를 받으면 Database에 Insert함<br>
 * @author eugenel, happy2v
 *
 */
public class GetMessagesTask extends AsyncNetTask {
	
	private UUIDMsg mViewUuid;
	private GetMessagesReq mGetMessageReq;

	/**
	 * 
	 * @param _context
	 * @param _uiHandler
	 */
	public GetMessagesTask(Context _context, Handler _uiHandler, UUIDMsg viewUuid, GetMessagesReq getMessagesReq) {
		super(_context, _uiHandler);
		this.mViewUuid = viewUuid;
		this.mGetMessageReq = getMessagesReq;
	}

	@Override
	protected TcpEnvelope onPreExecute() {		
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mGetMessageReq)
			.setMethodId(Session.Messaging.GetMessages)
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object requestObj,
			Object resultObj) {
		if(resultObj==null){
			return;	
		}
		
		TcpEnvelope tcpEnvelope = (TcpEnvelope) resultObj;
		GetMessagesRes messagesRes = (GetMessagesRes) tcpEnvelope.getMessage();
		
		MTalkLogWriter.d("GetMessagesTask ResponseCode : " + messagesRes.getResponseCode());
		
		if(messagesRes.getResponseCode()==Common.SUCCESS){
			
			ImageOption imageOption = new ImageOption();
			imageOption.setHeight(40);
			imageOption.setWidth(40);
			Message message = new Message();
			for(int i=0; i < messagesRes.getMessageCount(); i++){
				message = messagesRes.getMessage(i);
				if((GpbSupport.msbOf(mViewUuid) == GpbSupport.msbOf(message.getViewUuid())) 
						&& (GpbSupport.lsbOf(mViewUuid) == GpbSupport.lsbOf(message.getViewUuid()))){
					if(message.getType() == Common.MSG_TYPE_USER_MSG 
							&& message.getUserMassage().getContentType() == Common.CONTENT_TYPE_HTML){
						try{
							ThumbnailDownloadTask task = new ThumbnailDownloadTask(mContext, mUiHandler, InboxDatabaseHelper.getClientUUID(mContext, message.getViewUuid()),
									ChatDatabaseHelper.getClientMessageUuid(mContext, message.getMsgUuid()), message.getUserMassage().getAttachFile(), imageOption);
							task.execute();
						} catch (Exception e) {
							MTalkLogWriter.e(e);
						}
					}
					ChatDatabaseHelper.syncGetMessages(mContext, message);
				}
			}
			
			// 메시지가 더 있으면 더 요청 한다. // 이미 있는 데이터는 더 호출 할 필요가 없잖아?
			if(messagesRes.getMessageCount() >= ChatListActivity.GET_MESSAGE_MAX_COUNT
					&& ChatDatabaseHelper.checkMessage(mContext, mViewUuid, messagesRes.getMessageList())){
				UUIDSliceRange slice_range = new UUIDSliceRange();
				slice_range.setStart(messagesRes.getMessage(messagesRes.getMessageCount()-1).getNotiUuid());
				slice_range.setAscending(false);
				slice_range.setMaxCount(ChatListActivity.GET_MESSAGE_MAX_COUNT);

				GetMessagesReq getMessagesReq = new GetMessagesReq();
				getMessagesReq.setViewUuid(mViewUuid);
				getMessagesReq.setRange(slice_range);
				try{
					GetMessagesTask task = new GetMessagesTask(mContext, mUiHandler, mViewUuid, getMessagesReq);
					task.execute();
				} catch(Exception e) {
					MTalkLogWriter.e(e);
				}
			}
		}else{
			
		}
	}
}
